package com.catena.util;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler;

import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by hx-pc on 16-3-10.
 */
public class JsonUtil {

    private static final Object SYNC = new Object();
    private static ObjectMapper mapper;
    private static DeserializationProblemHandler handler = new DeserializationProblemHandler() {
        @Override
        public boolean handleUnknownProperty(DeserializationContext ctxt, JsonParser jp, JsonDeserializer<?> deserializer, Object beanOrClass, String propertyName) throws IOException {
            return true;
        }
    };

    static {
        if (mapper == null) {
            synchronized (SYNC) {
                if (mapper == null) {
                    mapper = new ObjectMapper()
                            .addHandler(handler)
                            .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
                            .configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true);
                }
            }
        }
    }

    private JsonUtil() {
    }

    public static String writeValueAsString(Object value) throws JsonProcessingException {
        return mapper.writeValueAsString(value);
    }

    public static void writeVaule(OutputStream out, Object value) throws IOException {
        mapper.writeValue(out, value);
    }

    public static <T> T readValue(byte[] src, Class<T> valueType) throws IOException {
        return mapper.readValue(src, valueType);
    }

    public static <T> T convertValue(Object fromValue, Class<T> toValueType) {
        return mapper.convertValue(fromValue, toValueType);
    }

    public static JsonUtil buildNewJsonUtil() {
        return new JsonUtil();
    }

    public static ObjectMapper getObjectMapper() {
        return mapper;
    }
}
